import React, { useState } from 'react';
import { Form, Input, Button, Toast } from 'antd-mobile';
import { useNavigate, Link } from 'react-router-dom';
import axios from '../../axios'; // 新增
import './Registration.css';

interface RegistrationFormValues {
  phone: string;
  password: string;
  confirmPassword: string;
  inviteCode: string;
  verificationCode: string;
  username: string;
}

const Registration: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm<RegistrationFormValues>();
  const [countdown, setCountdown] = useState<number>(0);

  // 验证手机号格式
  const validatePhone = (_: any, value: string): Promise<void> => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!value) {
      return Promise.reject(new Error('请输入手机号'));
    }
    if (!phoneRegex.test(value)) {
      return Promise.reject(new Error('请输入正确的手机号格式'));
    }
    return Promise.resolve();
  };

  // 获取验证码
  const handleGetVerificationCode = async () => {
    const phone = form.getFieldValue('phone');

    try {
      // 手动触发手机号验证
      await form.validateFields(['phone']);

      // TODO: 这里添加发送验证码的API调用
      Toast.show({
        icon: 'success',
        content: '验证码已发送',
      });

      // 开始倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error) {
      // 如果手机号验证失败，validateFields 会自动显示错误信息
      console.error('验证码发送失败:', error);
    }
  };

  const onFinish = async (values: RegistrationFormValues): Promise<void> => {
    try {
      // 注册请求
      const res = await axios.post('/bkc/register', {
        phone: values.phone,
        password: values.password,
        username: values.username
      });
      Toast.show({
        icon: 'success',
        content: '注册成功，正在自动登录...'
      });
      // 注册成功后自动登录
      const loginRes = await axios.post('/bkc/login', {
        userName: values.phone,
        passWord: values.password
      });
      if (loginRes.data?.data?.id) {
        localStorage.setItem('userId', loginRes.data.data.id);
      }
      navigate('/app/home');
    } catch (error: any) {
      Toast.show({
        icon: 'fail',
        content: error?.response?.data?.message || '注册失败，请重试',
      });
    }
  };

  const validatePassword = (_: any, value: string): Promise<void> => {
    if (!value) {
      return Promise.reject(new Error('请输入密码'));
    }
    if (value.length < 6) {
      return Promise.reject(new Error('密码长度至少6位'));
    }
    return Promise.resolve();
  };

  return (
    <div className="register-container">
      <div className="register-header">
        <h2>用户注册</h2>
        <p>社区团购平台</p>
      </div>
      <Form
        form={form}
        onFinish={onFinish}
        layout='vertical'
        footer={
          <Button block type='submit' color='primary' size='large'>
            注册
          </Button>
        }
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input placeholder='请输入用户名' maxLength={20} />
        </Form.Item>
        <Form.Item
          name="phone"
          label="手机号"
          rules={[{ validator: validatePhone }]}
        >
          <Input placeholder='请输入手机号' type="tel" maxLength={11} />
        </Form.Item>

        <Form.Item
          name="verificationCode"
          label="验证码"
          rules={[{ required: true, message: '请输入验证码' }]}
          extra={
            <Button
              size='small'
              onClick={handleGetVerificationCode}
              disabled={countdown > 0}
            >
              {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
            </Button>
          }
        >
          <Input placeholder='请输入验证码' maxLength={6} />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[{ validator: validatePassword }]}
        >
          <Input type='password' placeholder='请输入密码（至少6位）' />
        </Form.Item>

        <Form.Item
          name="confirmPassword"
          label="确认密码"
          rules={[
            { required: true, message: '请确认密码' },
            ({ getFieldValue }) => ({
              validator(_, value: string) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致'));
              },
            }),
          ]}
        >
          <Input type='password' placeholder='请再次输入密码' />
        </Form.Item>
      </Form>
      <div className="register-footer">
        <Link to="/login">已有账号？立即登录</Link>
      </div>
    </div>
  );
};

export default Registration; 